package com.littleorange.android.app.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.littleorange.android.app.R;
import com.littleorange.android.app.net.HttpPoster;
import com.littleorange.android.app.utils.Constants;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ShowCommodityActivity extends Activity {
	
	private ListView mListView = null;
	private String mCatagory = null;
	private List<Map<String, Object>> mData = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commodity_show);
		
		this.mCatagory = this.getIntent().getExtras().getString("catagory");
		String url = Constants.SERVER_URL + "/ws/commodity/list";
		this.mListView = (ListView)findViewById(R.id.listview_commodity_show);
		Map<String, String> data = new HashMap<String, String>();
		data.put("channel", "littleOrange");
		data.put("catagory", this.mCatagory);
		data.put("output", "json");
		this.mData = getData(url, data);
		
		SimpleAdapter sa = new SimpleAdapter(this, this.mData, R.layout.commodity_show_list, new String[]{"name", "description"}, new int[]{R.id.title_commodity_show_list, R.id.commodtiDescrption_commodity_show_list});
		this.mListView.setAdapter(sa);
	}
	
	private List<Map<String, Object>> getData(String url, Map<String, String> data){
		HttpPoster hper = new HttpPoster(url);
		String response = null;
		try {
			response = hper.post(data);
		} catch (ClientProtocolException e) {
			Log.e(Constants.LittltOrange_LOG, "ClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(Constants.LittltOrange_LOG, "IOException");
			e.printStackTrace();
		}
		
		Log.i(Constants.LittltOrange_LOG, "response : " + response);
		
		if(response != null){
			return decompileResponse(response);
		}
		
		return null;
	}
	
	private List<Map<String, Object>> decompileResponse(String response){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			JSONObject jo = new JSONObject(response);
			JSONArray ja = jo.getJSONArray("commoditylist");
			
			for(int i = 0; i != ja.length(); ++i){
				JSONObject tmp = ja.getJSONObject(i);
				Map<String, Object> d = new HashMap<String, Object>();
				d.put("name", tmp.getString("name"));
				d.put("description", tmp.getString("description"));
				list.add(d);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
}
